package org.example;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReentrantReadWriteLock;


public class Main {
    //创建 ReentrantReadWriteLock实例，用于创建读锁和写锁实例
    private static ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();
    //创建读锁实例
    private static ReentrantReadWriteLock.ReadLock readLock = reentrantReadWriteLock.readLock();
    //创建写锁实例
    private static ReentrantReadWriteLock.WriteLock writeLock = reentrantReadWriteLock.writeLock();
    //创建线程池
    private static ExecutorService threadPool = Executors.newCachedThreadPool();

    //获取的读锁方法
    public static void read() {
        //线程获取到读锁
        readLock.lock();
        System.out.println(Thread.currentThread().getName() + "获取读锁，开始执行");
        try {
            //睡眠3秒
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally {
            //释放读锁
            readLock.unlock();
            System.out.println(Thread.currentThread().getName() + "释放读锁，执行完成");
        }
    }
    //获取写锁的方法
    public static void write() {
        writeLock.lock();
        System.out.println(Thread.currentThread().getName() + "获取写锁，开始执行");
        try {
            //睡眠3秒
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally {
            //释放读锁
            writeLock.unlock();
            System.out.println(Thread.currentThread().getName() + "释放写锁，执行完成");
        }
    }
    public static void main(String[] args) {
        threadPool.submit(new Runnable() {
            @Override
            public void run() {
                write();
            }
        });
        threadPool.submit(new Runnable() {
            @Override
            public void run() {
                write();
            }
        });
    }
}